
<template>
    <base-node type="api_call" :config="props.data" :id="props.id" ref="baseNode">
        <template #default>
            <div class="node-config">
                <n-form
                    ref="formRef"
                    :model="props.data.apiCallConfig"
                    :rules="rules"
                    label-placement="top"
                    label-width="80"
                    require-mark-placement="right-hanging"
                >

                    <!-- Request method and URL -->
                    <n-form-item label="请求方式" path="method">
                        <n-select
                            v-model:value="props.data.apiCallConfig.method"
                            :options="methodOptions"
                            @update:value="handleMethodChange"
                        />
                    </n-form-item>

                    <n-form-item label="请求URL" path="url">
                        <n-input v-model:value="props.data.apiCallConfig.url" placeholder="https://api.example.com/endpoint" />
                    </n-form-item>

                    <!-- Request parameters -->
                    <n-form-item label="请求参数">
                        <div class="param-container">
                            <div v-if="showBodyEditor" class="body-editor-container">
                                <n-radio-group v-model:value="props.data.apiCallConfig.bodyType" size="small">
                                    <n-radio-button value="json">JSON</n-radio-button>
                                    <n-radio-button value="form">表单</n-radio-button>
                                    <n-radio-button value="raw">原始</n-radio-button>
                                </n-radio-group>

                                <div v-if="props.data.apiCallConfig.bodyType === 'json'" class="mt-2">
                                    <n-input
                                        v-model:value="props.data.apiCallConfig.jsonBody"
                                        type="textarea"
                                        placeholder="{ &quot;key&quot;: &quot;value&quot; }"
                                        :autosize="{ minRows: 3, maxRows: 10 }"
                                    />
                                </div>

                                <div v-else-if="props.data.apiCallConfig.bodyType === 'form'" class="param-list-container">
                                    <param-list
                                        v-model:params="props.data.apiCallConfig.formParams"
                                        :show-type="false"
                                        @add="addFormParam"
                                        @delete="deleteFormParam"
                                    />
                                </div>

                                <div v-else-if="props.data.apiCallConfig.bodyType === 'raw'" class="mt-2">
                                    <n-input
                                        v-model:value="props.data.apiCallConfig.rawBody"
                                        type="textarea"
                                        placeholder="请输入原始请求内容"
                                        :autosize="{ minRows: 3, maxRows: 10 }"
                                    />
                                </div>
                            </div>
                            <div v-else>
                                <param-list
                                    v-model:params="props.data.apiCallConfig.queryParams"
                                    :show-type="false"
                                    @add="addQueryParam"
                                    @delete="deleteQueryParam"
                                />
                            </div>
                        </div>
                    </n-form-item>

                    <!-- Request headers -->
                    <n-form-item label="请求头">
                        <param-list
                            v-model:params="props.data.apiCallConfig.headers"
                            :show-type="false"
                            @add="addHeader"
                            @delete="deleteHeader"
                        />
                    </n-form-item>

                    <!-- Response handling -->
                    <n-form-item label="响应处理">
                        <n-select
                            v-model:value="props.data.apiCallConfig.responseType"
                            :options="responseTypeOptions"
                        />
                    </n-form-item>
                </n-form>

                <!-- Test request button -->
<!--                <div class="action-buttons">-->
<!--                    <n-button size="small" type="primary" @click="testRequest">-->
<!--                        测试请求-->
<!--                    </n-button>-->
<!--                </div>-->
            </div>

        </template>

        <template #footer>
            <p class="tc-gray ">输出字段</p>
            <div class="output mt-8 pad-8 fx fx-c_center fx-m_between">
                <div class="fx fx-c_center">
                    <div class="output-flag noshrink"></div>
                    <n-input v-model:value="props.data.apiCallConfig.outputField" placeholder="字段名"
                             class="tc-gray ml-8 w-140"></n-input>
                </div>
                <span class="tc-assist">接口返回的数据</span>
            </div>
        </template>

        <template #source>
            <Handle type="source" id="success" :position="Position.Right"
                    style="transform: translate(50%, calc(-50% - 30px))" />
            <Handle type="source" id="fail" :position="Position.Right"
                    style="transform: translate(50%, calc(-50% + 30px))" />
        </template>
    </base-node>
</template>
<script setup>
	import {
		Position,
		Handle,
		useNode
	} from '@vue-flow/core'
    import {
        ref,
        watch,computed,
        onMounted,
        provide, inject
    } from "vue";
    import BaseNode from "@/views/app/chain/nodes/BaseNode.vue";
    import ParamList from '@/views/app/chain/nodes/action/cnps/ApiParamList.vue'
    const baseNode = ref(null);
	const props = defineProps(['id', 'data']) //默认配置

	provide('currentNodeId', props.id);

    provide("baseNode", baseNode)


    // Validation rules
    const rules = {
        url: {
            required: true,
            message: 'URL不能为空',
            trigger: 'blur'
        }
    }

    // Options for dropdowns
    const methodOptions = [
        { label: 'GET', value: 'GET' },
        { label: 'POST', value: 'POST' },
        // { label: 'PUT', value: 'PUT' },
        // { label: 'DELETE', value: 'DELETE' },
        // { label: 'PATCH', value: 'PATCH' },
        // { label: 'HEAD', value: 'HEAD' },
        // { label: 'OPTIONS', value: 'OPTIONS' }
    ]

    const responseTypeOptions = [
        { label: 'JSON', value: 'json' },
        { label: 'Text', value: 'text' },
        // { label: 'ArrayBuffer', value: 'arraybuffer' },
        // { label: 'Blob', value: 'blob' }
    ]

    // Computed properties
    const showBodyEditor = computed(() => {
        return ['POST', 'PUT', 'PATCH'].includes(props.data.apiCallConfig.method)
    })

    // Methods
    function handleMethodChange(value) {
        // Clear body data when switching to a method that doesn't support body
        if (!['POST', 'PUT', 'PATCH'].includes(value)) {
            props.data.apiCallConfig.jsonBody = ''
            props.data.apiCallConfig.rawBody = ''
            props.data.apiCallConfig.formParams = []
        }
    }

    // Parameter management
    function addQueryParam() {
        props.data.apiCallConfig.queryParams.push({ key: '', value: '' })
    }

    function deleteQueryParam(index) {
        props.data.apiCallConfig.queryParams.splice(index, 1)
    }

    function addFormParam() {
        props.data.apiCallConfig.formParams.push({ key: '', value: '' })
    }

    function deleteFormParam(index) {
        props.data.apiCallConfig.formParams.splice(index, 1)
    }

    function addHeader() {
        props.data.apiCallConfig.headers.push({ key: '', value: '' })
    }

    function deleteHeader(index) {
        props.data.apiCallConfig.headers.splice(index, 1)
    }


	onMounted(() => {
	})
</script>


<style scoped lang="scss">

.node-summary {
    display: flex;
    align-items: center;
    gap: 10px;
    height: 32px;
}

.method-badge {
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: bold;
    background-color: #e8e8e8;
    color: #666;
}

.method-badge.get {
    background-color: #d0f0fd;
    color: #0c8599;
}

.method-badge.post {
    background-color: #d3f9d8;
    color: #087f5b;
}

.method-badge.put {
    background-color: #fff3bf;
    color: #966600;
}

.method-badge.delete {
    background-color: #ffe3e3;
    color: #c92a2a;
}

.method-badge.patch {
    background-color: #e5dbff;
    color: #5f3dc4;
}

.url-display {
    flex: 1;
    font-size: 13px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.text-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.node-config {
    padding-top: 10px;
}

.param-container {
    width: 100%;
    border: 1px solid #eee;
    border-radius: 4px;
    padding: 8px;
}

.param-list-container {
    margin-top: 8px;
}

.body-editor-container {
    display: flex;
    flex-direction: column;
}

.mt-2 {
    margin-top: 8px;
}

.action-buttons {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}

</style>